﻿using BLL;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Web;
using System.Web.Mvc;
using webui.Models; 
using Tools;

namespace webui
{
    public class OperateContext
    {
         

        public UserInfoBLL iuserbll = new UserInfoBLL();
        public UserRoleBLL iuserrole = new UserRoleBLL();
        public RolePermissionBLL irolepermis = new RolePermissionBLL();
        public PermissionBLL ipermiss = new PermissionBLL();
        public UserVipPermissionBLL iuservip = new UserVipPermissionBLL();

        const string Admin_CookiePath = "/admin/";
        const string Admin_InfoKey = "ainfo";
        const string Admin_PermissionKey = "apermission";
        const string Admin_TreeString = "aTreeString";
        const string Admin_LogicSessionKey = "BLLSession";
        const string key = "kongdeliang";
       public const string adminstr = "admin";

        #region 0.1 Http上下文 及 相关属性
        /// <summary>
        /// Http上下文
        /// </summary>
        public  HttpContext ContextHttp
        {
            get
            {
                return HttpContext.Current;
            }
        }

        HttpResponse Response
        {
            get
            {
                return ContextHttp.Response;
            }
        }

        HttpRequest Request
        {
            get
            {
                return ContextHttp.Request;
            }
        }

        System.Web.SessionState.HttpSessionState Session
        {
            get
            {
                return ContextHttp.Session;
            }
        }
        #endregion


        #region 0.4 获取当前 操作上下文 + OperateContext Current
        /// <summary>
        /// 获取当前 操作上下文 (为每个处理浏览器请求的服务器线程 单独创建 操作上下文)
        /// </summary>
        public static OperateContext Current
        {
            get
            {
                OperateContext oContext = CallContext.GetData(typeof(OperateContext).Name) as OperateContext;
                if (oContext == null)
                {
                    oContext = new OperateContext();
                    CallContext.SetData(typeof(OperateContext).Name, oContext);
                }
                return oContext;
            }
        }
        #endregion
        #region 2.0 根据用户id查询用户权限 +List<MODEL.Ou_Permission> GetUserPermission(int usrId)
        /// <summary>
        /// 根据用户id查询用户权限
        /// </summary>
        /// <param name="usrId"></param>
        public List<Permission> GetUserPermission(int usrId)
        {
            //-------A.根据用户角色查询
            //1.0 根据用户 id 查到 该用户的 角色id
 
            List<int> listRoleId = iuserrole.GetList(ur => ur.uid == usrId).Select(ur => ur.rid).ToList();
            //2.0 根据角色 id 查询角色权限 id
            List<int> listPerIds = irolepermis.GetList(rp => listRoleId.Contains(rp.rid)).Select(rp => rp.pId).ToList();
            //3.0 查询所有角色数据
            List<Permission> listPermission = ipermiss.GetList(p => listPerIds.Contains(p.Id));
            //-------B.根据用户特权查询
            //b.1 查询 用户特权id
            List<int> vipPerIds = Current.iuservip.GetList(vip => vip.uid == usrId).Select(vip => vip.pId).ToList();
            //b.2 查询 特权数据
           List<Permission> listPermission2 = ipermiss.GetList(p => vipPerIds.Contains(p.Id)).ToList();
            //-------C.将两个权限集合 合并（将集合2的权限数据 添加到 集合1中）
            listPermission2.ForEach(p =>
            {
                listPermission.Add(p);
            });
            return listPermission.OrderBy(u => u.pOrder).ToList();
        }
        #endregion


        #region 2.1 当前用户对象 +MODEL.UserInfo Usr 存放到Session
        /// <summary>
        /// 当前用户对象
        /// </summary>
        public UserInfo Usr
        {
            get
            {
                return Session[Admin_InfoKey] as UserInfo;
            }
            set
            {
                Session[Admin_InfoKey] = value;
            }
        }
        #endregion

        #region 0.3 用户权限 +List<MODEL.Ou_Permission> UsrPermission
        // <summary>
        /// 用户权限
        /// </summary>
        public List<Permission> UsrPermission
        {
            get
            {
                return Session[Admin_PermissionKey] as List<Permission>;
            }
            set
            {
                Session[Admin_PermissionKey] = value;
            }
        }
        #endregion


        #region 2.1 管理员登录方法 + bool LoginAdmin(MODEL.ViewModel.LoginUser usrPara)
        /// <summary>
        /// 管理员登录方法
        /// </summary>
        /// <param name="usrPara"></param>
        public bool LoginAdmin(ViewModel.v_LoginUser usrPara)
        {
            //到业务成查询
            UserInfo usr = iuserbll.Login(usrPara.LoginName, usrPara.Pwd);
            if (usr != null)
            {
                //2.1 保存 用户数据(Session or Cookie)
                Usr = usr;
                //如果选择了复选框，则要使用cookie保存数据
                if (usrPara.IsAlways)
                {
                    //2.1.2将用户id加密成字符串
                    string strCookieValue =  Tools.Security.MD5(usr.id.ToString());
                    //2.1.3创建cookie
                    HttpCookie cookie = new HttpCookie(Admin_InfoKey, strCookieValue);
                    cookie.Expires = DateTime.Now.AddDays(1);
                    cookie.Path = Admin_CookiePath;
                    Response.Cookies.Add(cookie);
                }
                //2.2 查询当前用户的 权限，并将权限 存入 Session 中
                UsrPermission = GetUserPermission(usr.id);
                return true;
            }
            return false;
        }
        #endregion
        
        /// <summary>
        /// 判断当前用户是否登陆 而且
        /// </summary>
        /// <returns></returns>
        public bool IsLogin()
        {
            //1.验证用户是否登陆(Session && Cookie)
            if (Session[Admin_InfoKey] == null)
            {
                if (Request.Cookies[Admin_InfoKey] == null)
                {
                    return false;
                }
                else//如果有cookie则从cookie中获取用户id并查询相关数据存入 Session
                {
                    string strUserInfo = Request.Cookies[Admin_InfoKey].Value;
                    strUserInfo = Tools.Security.DeMD5(strUserInfo);
                    int userId = int.Parse(strUserInfo);
                    UserInfo usr = iuserbll.GetList(u => u.id == userId).FirstOrDefault();
                    Usr = usr;  //设置 session
                    UsrPermission = OperateContext.Current.GetUserPermission(usr.id);
                }
            }
            return true;
        }

        
        /// <summary>
        /// 2.3 判断当前用户 是否有 访问当前页面的权限
        /// </summary> 
        /// <param name="areaName"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        /// <param name="httpMethod"></param>
        /// <returns></returns>
        public bool HasPemission(string areaName, string controllerName, string actionName, string httpMethod)
        {
            //var listP = from per in UsrPermission
            //            where
            //                string.Equals(per.pAreaName, areaName, StringComparison.CurrentCultureIgnoreCase) &&
            //                string.Equals(per.pControlName, controllerName, StringComparison.CurrentCultureIgnoreCase) &&
            //                string.Equals(per.pActionName, actionName, StringComparison.CurrentCultureIgnoreCase) 
            //                //&& (
            //                //    per.pFormMethod == 3 ||//如果数据库保存的权限 请求方式 =3 代表允许 get/post请求
            //                //    per.pFormMethod == (httpMethod.ToLower() == "get" ? 1 : 2)
            //                //)
            //            select per;

          var  listP = from per in UsrPermission
                    where
                        string.Equals(per.pAreaName, areaName, StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(per.pControlName, controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                        string.Equals(per.pActionName, actionName, StringComparison.CurrentCultureIgnoreCase)

                    select per;


            // var listP = UsrPermission.Where(s => s.pAreaName.ToUpper() == areaName.ToUpper() && s.pControlName.ToUpper() == controllerName.ToUpper() && s.pActionName.ToUpper() == actionName.ToUpper());

            return listP.Count() > 0;
        }
       
        /// <summary>
        /// 获取当前登陆用户的权限树Json字符串
        /// </summary>
        public string UsrTreeJsonStr
        {
            get
            {
                if (Session[Admin_TreeString] == null || Session[Admin_TreeString].ToString() == "")
                {
                    //将 登陆用户的 权限集合 转成 树节点 集合（其中 IsShow = false的不要生成到树节点集合中）
                    List<TreeNode> listTree = Permission.ToTreeNodes(UsrPermission.Where(p => p.pIsShow == true).OrderBy(p => p.pOrder).ToList());
                    Session[Admin_TreeString] = listTree.ToJson(); 
                }
                return Session[Admin_TreeString].ToString();
            }
        }

      
        /// <summary>
        /// 生成 Json 格式的返回值
        /// </summary>
        /// <param name="statu"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <param name="backurl"></param>
        /// <returns></returns>
        public ActionResult RedirectAjax(int statu, string msg, object data, string backurl)
        {
           
            AjaxMsgModel ajax = new AjaxMsgModel()
            {
                Status = statu,
                Msg = msg,
                Data = data,
                BackUrl = backurl
            };
            JsonResult res = new JsonResult();
            res.Data = ajax;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return res;
        }

        /// <summary>
        /// 生成 Json 格式的返回值
        /// </summary>
        /// <param name="statu"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <param name="backurl"></param>
        /// <returns></returns>
        public ActionResult RedirectAjax(string statu, string msg, object data, string backurl)
        {
            AjaxMsgModelOLD ajax = new AjaxMsgModelOLD()
            {
                Status = statu,
                Msg = msg,
                Data = data,
                BackUrl = backurl
            };
            JsonResult res = new JsonResult();
            res.Data = ajax;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return res;
        }


        /// <summary>
        /// 重定向方法 有两种情况：如果是Ajax请求，则返回 Json字符串；如果是普通请求，则 返回重定向命令
        /// </summary>
        /// <returns></returns>
        public ActionResult Redirect(string url, ActionDescriptor action)
        {
            //如果Ajax请求没有权限，就返回 Json消息
            if (action.IsDefined(typeof(AjaxRequestAttribute), false)
            || action.ControllerDescriptor.IsDefined(typeof(AjaxRequestAttribute), false))
            {
                return RedirectAjax("nologin", "您没有登陆或没有权限访问此页面~~", null, url);
            }
            else//如果 超链接或表单 没有权限访问，则返回 302重定向命令
            {
                return new RedirectResult(url);
            }
        }
        
        /// <summary>
        /// 返回分页按钮条
        /// </summary>
        /// <param name="pageSize">页大小</param>
        /// <param name="currentPage">当前页码</param>
        /// <param name="totalCount">一共有多少条</param>
        /// <returns></returns>
        public static string ShowPageNavigate(int pageSize, int currentPage, int totalCount)
        {
            string redirectTo = "";
            pageSize = pageSize == 0 ? 3 : pageSize;
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数
            var output = new StringBuilder();
            if (totalPages > 1)
            {
                if (currentPage != 1)
                {//处理首页连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize);
                }
                if (currentPage > 1)
                {//处理上一页的连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize);
                }
                else
                {
                    // output.Append("<span class='pageLink'>上一页</span>");
                }

                output.Append(" ");
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {//一共最多显示10个页码，前面5个，后面5个
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                    {
                        if (currint == i)
                        {//当前页处理
                            //output.Append(string.Format("[{0}]", currentPage));
                            output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
                        }
                        else
                        {//一般页处理
                            output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
                        }
                    }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {//处理下一页的链接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize);
                }
                else
                {
                    //output.Append("<span class='pageLink'>下一页</span>");
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize);
                }
                output.Append(" ");
            }
            output.AppendFormat("<a class='gpb'>第{0}页 / 共{1}页 </a>", currentPage, totalPages);//这个统计加不加都行
            return output.ToString();
        }
        

    }
  
}